XfMissionChapterExecute={
	private ["_chapter_succeeded"];
	diag_log "";
	diag_log "=========================================================================";
	diag_log "                             CHAPTER 1                                   ";
	diag_log "=========================================================================";
	diag_log "";
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Starting Chapter","_last_random_reinforcement","_random_reinf_diff","_reinforcement_power"];
	DM_Mission_ArtilleryVariables = [];
	DM_Mission_Chapter_CanRun = True;
	DM_Mission_Chapter_Runs = True;
	DM_Mission_Chapter_Success = 0;
	call XfMissionChapterSetup;
	_chapter_succeeded = false;
	if (!DM_Mission_Mission_CanRun) exitWith {diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Mission canceled!"];};
	

	_player_detected = false;
	_flag_captured = false;
	
	_enemy_initial_counts = ([DM_Chapter_Position,400,d_enemy_side] call XfMissionGetZoneSideCount) select 0;
	_unique_id = 0;
	_reinforcements = 10;
	_detected_time = time;
	_reinforcement_trigger = _enemy_initial_counts / 4;
	diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Entering the loop",[_enemy_initial_counts,_reinforcement_trigger], Time];
	_flag_type = typeof DM_Target;
	while {DM_Mission_Chapter_CanRun AND DM_Mission_Mission_CanRun} do {
		sleep 10;
		_enemy_counts = ([DM_Chapter_Position,400,d_enemy_side] call XfMissionGetZoneSideCount) select 0;
		
		if (["jip_player_detected",false] call XNetGetJIP) then {_player_detected = true;};
		
		_flags = (getPos FLAG_BASE) nearObjects [_flag_type, 200];
		if (count _flags > 0) then {
			{
				_action_type = _x call XfMissionGetAction;
				if (_action_type == "PICKUP") exitwith {
					_flag_captured = true;
				};
			} foreach _flags;
		};
		
		if (_flag_captured) then {
			["CaptureTheFlag","", "","",[],"Succeeded"] call XfMissionTask;
			_chapter_succeeded = true;
			DM_Mission_Chapter_CanRun = false;
			sleep 15;
		};
		
		if (DM_Mission_Chapter_CanRun AND _player_detected and !_detected_updated) then {
			_detected_updated = true;
			"You are detected! Reinforcements will surely be called!" call XfMissionMessageToAll;
			_detected_time = time;
		};
		// diag_log Format["(%1)[%2]: %3: %4: en:%5  kill:%6  det:%7  flee:%8",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Loop",_enemy_counts,_dealer_killed,_player_detected,_dealer_fleeing];
		If (DM_Mission_Chapter_CanRun AND _player_detected AND (_reinforcements != 0) AND !_tower_destroyed) then {
			// If the player is detected and no reinforcement is on the way.. Then we send new troops in :)
			if ((_enemy_initial_counts - _enemy_counts) > _reinforcement_trigger) then {
				if (_unique_id == 0) then {
					// If the reinforcement function returns a value greater than 0, it means a reinforcement was created!
					_unique_id = [d_enemy_side,[DM_Chapter_Position,200],"RANDOM",DM_Mission_RandomReinforcement] call XfMissionCallReinforcement;
					if ((_unique_id) > 0) then {
						diag_log Format["(%1)[%2]: %3: %4: reinf:%5, diff:%6, ini:%7, vec:%8",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Sending reinforcement",_reinforcements,_enemy_diff,_enemy_initial_counts];
						_reinforcements = _reinforcements - 1;
						// hint "Reinforcement";
					};
				};
			} else {
				_unique_id = 0;
			};
		};
	};
	
	if (DM_Mission_Mission_CanRun) then {
		if (_chapter_succeeded) then {
			call XfMissionChapterSuccess;
		} else {
			call XfMissionChapterFailure;
		};
	} else {
		diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Mission canceled!"];
	};

	// Just in case a reinforcement is already on the way.
	call XfMissionCancelReinforcement;
	call XfMissionChapterCleanUp;
	DM_Mission_Chapter_Runs = False;
};

XfMissionChapterSetup={
	private ["_random_town","_random_town_pos","_random_town_size","_troops_power","_troops_coeff","_grpSoldiers","_grpVehicle","_i"];
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Starting Initialization"];

	// We filter only towns (the bigger ones)
	_random_town = [true] call XfMissionGetRandomTown;
	if ((count _random_town) <= 0) exitWith {"Could not pick a random town" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	while {(_random_town_pos distance FLAG_BASE) < 700} do {
		_random_town = [true] call XfMissionGetRandomTown;
	};
	_random_town_pos = _random_town select 0;
	
	DM_Chapter_Position = _random_town_pos;
	DM_Chapter_Location = _random_town;
	_random_town_size = _random_town select 3;
	_random_town_name = _random_town select 1;
	diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Selected Town:",_random_town];

	// This indicates where the mission takes place
	[_random_town_pos,_random_town_size,_random_town_name] call XfMissionCurrentPosition;
	
	// We search a spot to place the teleporter which is around the town on a road (to avoid mountains and forests)
	_teleporter = [_random_town_pos] call XfMissionRandomStartTeleporter;
	// If no spot found, we get back an empty position.
	if (count (_teleporter select 0) > 0) then {
		[false,["chapter1_start_position",(_teleporter select 0), "ICON", "ColorBlue", [1,1],"",(_teleporter select 1),"hd_start","",1]] call XfMissionMarker;
	};

	// upsmon zone
	[true,["chapter1_random_town_zone", _random_town_pos, "ELLIPSE", "ColorRed", [_random_town_size * 1.5,_random_town_size * 1.5],"",0,"","BDiagonal",0.5]] call XfMissionMarker;
	// target zone
	[false,["chapter1_town_zone", _random_town_pos, "ELLIPSE", "ColorRed", [_random_town_size,_random_town_size],"",0,"","BDiagonal",0.5]] call XfMissionMarker;
	[false,["chapter1_town_cross",_random_town_pos, "ICON", "ColorRed", [1,1],"",20,"hd_destroy","",0.6]] call XfMissionMarker;
	
	_bunker_count = 2 + floor(random(2));
	_bunkers = [];
	_flag_type = switch (d_enemy_side) do {
		case "WEST": {"FlagCarrierUSA"};
		case "EAST": {"FlagCarrierRU"};
		case "GUER": {"FlagCarrierGUE"};
		default {"FlagCarrierINS"};
	};

	_spot = [_random_town_pos,(_random_town_size / 2),_flag_type,_random_town_pos] call  XfMissionRanObjectivePos;
	if (count _spot == 0) then { _spot = _random_town_pos; };
	["jip_target_pickup",false] call XNetSetJIP;
	DM_Target = [_flag_type,_spot,"PICKUP",["Town's Flag","You caught the Flag!","jip_target_pickup","Take the Flag",True]] call XfMissionCreateMissionObject;
	["CaptureTheFlag","Capture the Flag", "You need to take the Flag from the town and place it back at your base!","",[],"Created"] call XfMissionTask;

	[d_enemy_side,[_random_town_pos,_random_town_size],true,0,0,1,0] call XfMissionPopulateLocation;
	// The trigger which will send reinforcement when the player is detected!
	["jip_player_detected",false] call XNetSetJIP;
	[_random_town_pos,_random_town_size * 2,d_own_side,d_enemy_side,"jip_player_detected"] call XfMissionSideDetected;
	// This will create snipers automatically if selected in the mission setup
	[d_enemy_side,[_random_town_pos,_random_town_size],DM_Mission_Snipers] call XfMissionCreateSnipersArea;
	// This will create air support automatically if selected in the mission setup
	[d_enemy_side,[_random_town_pos,_random_town_size],DM_Mission_AirSupport] call XfMissionCallAirSupport;
	// We will spawn civilians in a zone slightly smaller than the town.
	[[_random_town_pos,_random_town_size * 0.8],d_enemy_side,_amount] call XfMissionCivilianSpawn;
};

XfMissionChapterSuccess={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSuccess","Starting"];
	"Congratulations! You captured the Flag! This will be a devastating blow for our enemy's moral!" call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = 1;
};

XfMissionChapterFailure={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterFailure","Starting"];
	"You tried but failed... you'll do better next time." call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = -1;
};

// Self-explanatory
XfMissionChapterCleanUp={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterCleanUp","Starting"];
	// Giving an empty position places the teleporter back to the hangar, closing the hangar.
	[[],0] call XfMissionPlaceStartTeleporter;
	[] call XfMissionCleanMarkers;
	[] call XfMissionCleanTriggers;
	[] call XfMissionCleanTasks;
};

DM_Mission_Chapter_Compiled = true;